﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mime;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using System.Xml.Serialization;
using WkHtmlToXSharp;

namespace DentScan2.WebApp
{
    public partial class Form : Classes.BaseForm
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string guid = Request.QueryString["uid"];
            Classes.Damage dmg = null;
            if (!string.IsNullOrEmpty(guid) && Cache[guid] != null)
            {
                string damageId = Cache[guid].ToString();
                dmg = new Classes.Damage(dl.Damages.First(d => d.DamageId == Guid.Parse(damageId)));
            }
            else
            {
                guid = Request.QueryString["auid"];
                if (!string.IsNullOrEmpty(guid) && Cache[guid] != null)
                {
                    string damageArchiveId = Cache[guid].ToString();
                    XElement xe = dl.DamageArhives.First(da => da.DamageArhiveId == Guid.Parse(damageArchiveId)).DamageXml;
                    dmg = Classes.Damage.FromXml(xe);
                }

            }
            if (dmg == null)
                return;
            string areaId = Request.QueryString["areaId"];
            DB.Area area = dl.Areas.First(a => a.AreaId == Guid.Parse(areaId));

            dmg.VAT = area.VAT;
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            XmlSerializer xs = new XmlSerializer(typeof(Classes.Damage));
            xs.Serialize(sw, dmg);
            string s = Tools.Tools.XslTransform(sb.ToString(), Server.MapPath("Xslt/Form.xslt"));
            byte[] bytes = null;
            using (var pdfConverter = new MultiplexingConverter())
            {

                pdfConverter.ObjectSettings.Web.DefaultEncoding = "utf-8";
                bytes = pdfConverter.Convert(s);
            }
            //Response.Clear();
            Response.ContentType = MediaTypeNames.Application.Pdf;
            Response.AddHeader("Content-Disposition", "inline;filename=Form.pdf");
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();


        }
    }
}